package com.hancher.gamelife2.matter;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;

import androidx.recyclerview.widget.RecyclerView;
import androidx.sqlite.db.SimpleSQLiteQuery;

import com.github.gzuliyujiang.calendarpicker.CalendarPicker;
import com.hancher.common.androidutil.AsyncUtils;
import com.hancher.common.androidutil.LogUtil;
import com.hancher.common.androidutil.ToastUtil;
import com.hancher.common.base.BaseMvpFragment;
import com.hancher.common.javautil.DateUtil;
import com.hancher.common.javautil.EmptyUtil;
import com.hancher.common.room.DbFiliter;
import com.hancher.common.rv.PageRecyclerViewManager;
import com.hancher.gamelife2.R;
import com.hancher.gamelife2.databinding.FragmentMatterBinding;
import com.hancher.gamelife2.function.FunctionPresenter;
import com.hancher.gamelife2.main.MainDatabase_Impl;
import com.kongzue.dialogx.dialogs.InputDialog;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.enums.PopupPosition;
import com.yanzhenjie.recyclerview.touch.OnItemMoveListener;
import com.yanzhenjie.recyclerview.touch.OnItemStateChangedListener;

import java.util.Collections;
import java.util.List;

import io.reactivex.rxjava3.functions.Consumer;

/**
 * 描述 : 事项清单 <br/>
 * 时间 : 2023/11/26 17:02 <br/>
 * 作者 : Hancher ytu_shaoweijie@163.com
 */
public class MatterFragment extends BaseMvpFragment<FragmentMatterBinding, FunctionPresenter> {

    PageRecyclerViewManager<MatterPO> prvmTodo;
    PageRecyclerViewManager<MatterPO> prvmFinished;
    DbFiliter filiter = new DbFiliter();

    @Override
    protected void initView(Bundle savedInstanceState) {
        // 待办事项
        prvmTodo = new PageRecyclerViewManager<MatterPO>()
                .setContext(getContext())
                .setRecyclerView(binding.recyclerView2)
                .setAdapter(new MatterAdapter())
                .setOnItemClickListener((baseQuickAdapter, view, i) -> {
                    new XPopup.Builder(getContext())
                            //.maxWidth(600)
                            .atView(view)
                            .popupPosition(PopupPosition.Right)
                            .hasShadowBg(false)
                            .animationDuration(0)
                            .asAttachList(new String[]{"完成", "编辑", "置顶", "删除"},
                                    new int[]{R.drawable.icon_note, R.drawable.icon_top, R.drawable.icon_delete, R.drawable.icon_done},
                                    (position, text) -> {
                                        ToastUtil.show("click " + text);
                                        if (position == 0) {
                                            changeItemStatus(i);
                                        } else if (position == 1) {
                                            modifyItem(i);
                                        } else if ((position == 2)) {
                                            topItem(i);
                                        } else if ((position == 3)) {
                                            deleteItem(i);
                                        }
                                    })
                            .show();
                })
                .init();

        binding.recyclerView2.setLongPressDragEnabled(true);
        binding.recyclerView2.setOnItemMoveListener(new OnItemMoveListener() {
            @Override
            public boolean onItemMove(RecyclerView.ViewHolder srcHolder, RecyclerView.ViewHolder targetHolder) {
                // 此方法在Item拖拽交换位置时被调用。
                // 第一个参数是要交换为之的Item，第二个是目标位置的Item。

                // 交换数据，并更新adapter。
                int fromPosition = srcHolder.getAdapterPosition();
                int toPosition = targetHolder.getAdapterPosition();
                Collections.swap(prvmTodo.getRvList(), fromPosition, toPosition);
                prvmTodo.getAdapter().notifyItemMoved(fromPosition, toPosition);
                // 返回true，表示数据交换成功，ItemView可以交换位置。
                return true;
            }

            @Override
            public void onItemDismiss(RecyclerView.ViewHolder srcHolder) {

            }
        });
        //手指抬起时，处理数据库数据
        binding.recyclerView2.setOnItemStateChangedListener((viewHolder, actionState) -> {
            if (actionState == OnItemStateChangedListener.ACTION_STATE_IDLE) {
                AsyncUtils.run(emitter -> {
                    for (int i = 0; i < prvmTodo.getRvList().size(); i++) {
                        prvmTodo.getRvList().get(i).setSort(Long.valueOf(i));
                    }
                    MainDatabase_Impl.getInstance().matterDao().updateList(prvmTodo.getRvList());
                    queryTodoList();
                }, (Consumer<Object>) o -> {

                });
            }
        });

        //已办事项
        prvmFinished = new PageRecyclerViewManager<MatterPO>()
                .setContext(getContext())
                .setRecyclerView(binding.recyclerView3)
                .setAdapter(new MatterAdapter())
                .setOnItemClickListener((baseQuickAdapter, view, i) -> {
                    AsyncUtils.run(emitter -> {
                        MatterPO item = prvmFinished.getRvList().get(i);
                        item.setStatus(0);
                        item.setFinishTime(null);
                        MainDatabase_Impl.getInstance().matterDao().updateItem(item);
                        emitter.onComplete();
                    }, o -> {

                    });
                })
                .init();
    }

    @SuppressLint("CheckResult")
    @Override
    protected void initData() {
        LogUtil.d("查询数据");
        filiter.setStart(DateUtil.getFirstStampOfToday());
        filiter.setEnd(DateUtil.getFirstStampOfToday(1));
        queryTodoList();
        queryFinishList();
    }


    @Override
    protected void initListener() {
//        binding.imgBackup.setOnClickListener(v -> {
//            Navigation.findNavController(binding.matterContain).navigate(R.id.action_matterFragment_to_backupFragment);
//        });
        binding.imgEdit.setOnClickListener(v -> {
            addItem();
        });
        binding.tvFinishedTitle.setOnClickListener(v -> {
            CalendarPicker picker = new CalendarPicker(getActivity());
//            picker.setRangeDateOnFuture(3);
//            if (singleTimeInMillis == 0) {
//                singleTimeInMillis = System.currentTimeMillis();
//            }
            picker.setSelectedDate(System.currentTimeMillis());
            picker.setOnSingleDatePickListener(date -> {
                long diffDay = DateUtil.getDiffDay(date.getTime(), System.currentTimeMillis());
                binding.tvFinishedTitle.setText(DateUtil.stamp2YmdStr(date.getTime()));
                filiter.setStart(DateUtil.getFirstStampOfToday((int) diffDay));
                filiter.setEnd(DateUtil.getFirstStampOfToday((int) (1 + diffDay)));
                queryFinishList();
            });
            picker.show();
        });
        binding.etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                LogUtil.d("字符串变化：" + s.toString());
                binding.imgClear.setVisibility(EmptyUtil.isNotEmpty(s.toString()) ? View.VISIBLE : View.GONE);
                filiter.setSearch(s.toString());
                queryFinishList();
                queryTodoList();
            }
        });
        binding.imgClear.setOnClickListener(v -> binding.etSearch.setText(""));
    }

    //region 查询
    private void queryTodoList() {
        StringBuffer sqlStr = new StringBuffer(" SELECT * FROM matter WHERE deleteflag!=1 AND status!=1 ");
        if (EmptyUtil.isNotEmpty(binding.etSearch.getText().toString())) {
            sqlStr.append(" AND title like '%").append(binding.etSearch.getText().toString()).append("%' ");
        }
        sqlStr.append(" ORDER BY sort, createTime ");
        AsyncUtils.run(emitter -> {
            List<MatterPO> data = MainDatabase_Impl.getInstance().matterDao().getFinishedList(new SimpleSQLiteQuery(sqlStr.toString()));
            emitter.onNext(data);
            emitter.onComplete();
        }, (Consumer<List<MatterPO>>) data -> {
            LogUtil.d("未完成事项发生变化：" + data.size());
            prvmTodo.freshData(data);
        });
    }

    private void queryFinishList() {
        StringBuffer sqlStr = new StringBuffer(" SELECT * FROM matter WHERE deleteflag!=1 AND status=1 ")
                .append(" AND finishTime BETWEEN ").append(filiter.getStart()).append(" AND ").append(filiter.getEnd());
        if (EmptyUtil.isNotEmpty(binding.etSearch.getText().toString())) {
            sqlStr.append(" AND title like '%").append(binding.etSearch.getText().toString()).append("%' ");
        }
        sqlStr.append(" ORDER BY finishTime ");
        AsyncUtils.run(emitter -> {
            List<MatterPO> data = MainDatabase_Impl.getInstance().matterDao().getFinishedList(new SimpleSQLiteQuery(sqlStr.toString()));
            emitter.onNext(data);
            emitter.onComplete();
        }, (Consumer<List<MatterPO>>) data -> {
            LogUtil.d("已完成事项发生变化：" + data.size());
            prvmFinished.freshData(data);
        });
    }
    //endregion

    //region 修改
    private void modifyItem(int i) {
        new InputDialog("修改事项", null, "修改", "取消")
                .setInputText(prvmTodo.getRvList().get(i).getTitle())
                .setOkButtonClickListener((dialog, v, inputStr) -> {
                    // 修改
                    AsyncUtils.run(emitter -> {
                        MatterPO item = prvmTodo.getRvList().get(i);
                        item.setTitle(inputStr);
                        item.setUpdateTime(System.currentTimeMillis());
                        MainDatabase_Impl.getInstance().matterDao().updateItem(item);
                        emitter.onNext("");
                        emitter.onComplete();
                    }, (Consumer<String>) s -> {
                        if (dialog != null && dialog.isShow()) {
                            dialog.dismiss();
                        }
                        queryTodoList();
                    });
                    return true;
                })
                .setCancelable(true)//点击外部遮罩，关闭弹窗
                .show();
    }

    private void topItem(int i) {
        AsyncUtils.run(emitter -> {
            for (int j = 0; j < prvmTodo.getRvList().size(); j++) {
                prvmTodo.getRvList().get(j).setSort((long) (j + 1));
                prvmTodo.getRvList().get(j).setUpdateTime(System.currentTimeMillis());
            }
            prvmTodo.getRvList().get(i).setSort(0L);
            prvmTodo.getRvList().get(i).setUpdateTime(System.currentTimeMillis());
            MainDatabase_Impl.getInstance().matterDao().updateList(prvmTodo.getRvList());
            emitter.onNext("");
            emitter.onComplete();
        }, (Consumer<String>) s -> {
            queryTodoList();
        });
    }


    private void deleteItem(int i) {
        AsyncUtils.run(emitter -> {
            MatterPO item = prvmTodo.getRvList().get(i);
            item.setDeleteflag((byte) 1);
            item.setUpdateTime(System.currentTimeMillis());
            MainDatabase_Impl.getInstance().matterDao().updateItem(item);
            emitter.onNext("");
            emitter.onComplete();
        }, o -> {
            queryTodoList();
        });
    }

    private void changeItemStatus(int i) {
        AsyncUtils.run(emitter -> {
            MatterPO item = prvmTodo.getRvList().get(i);
            item.setStatus(1);
            item.setUpdateTime(System.currentTimeMillis());
            item.setFinishTime(System.currentTimeMillis());
            MainDatabase_Impl.getInstance().matterDao().updateItem(item);
            emitter.onNext("");
            emitter.onComplete();
        }, o -> {
            queryTodoList();
            queryFinishList();
        });
    }
    //endregion


    //region 添加
    private void addItem() {
        // 编辑框
        new InputDialog("添加事项", null, "添加后继续添加", "添加")
                .setOkButtonClickListener((dialog, v, inputStr) -> {
                    //  添加一条道数据库，并且重新弹窗
                    AsyncUtils.run(emitter -> {
                        MatterPO item = new MatterPO();
                        item.setTitle(inputStr);
                        MainDatabase_Impl.getInstance().matterDao().insertItem(item);
                        if (EmptyUtil.isEmpty(dialog.getMessage())) {
                            emitter.onNext(inputStr);
                        } else {
                            emitter.onNext(dialog.getMessage() + "\n" + inputStr);
                        }
                        emitter.onComplete();
                    }, (Consumer<String>) s -> {
                        dialog.setMessage(s);
                        queryTodoList();
                    });
                    return true;
                })
                .setCancelButtonClickListener((dialog, v, inputStr) -> {
                    // 添加一条到数据库
                    AsyncUtils.run(emitter -> {
                        MatterPO item = new MatterPO();
                        item.setTitle(inputStr);
                        MainDatabase_Impl.getInstance().matterDao().insertItem(item);
                        emitter.onNext("");
                        emitter.onComplete();
                    }, (Consumer<String>) s -> {
                        queryTodoList();
                    });
                    return false;
                })
                .setCancelable(true)//点击外部遮罩，关闭弹窗
                .show();
    } 
    //endregion

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}